#!/usr/bin/env bash

# For the license, see the LICENSE file in the root directory.

if [ "$(id -u)" -ne 0 ]; then
        echo "Need to be root to run this test."
        exit 77
fi

if [ "$(uname -s)" != "Linux" ]; then
	# Due to using /proc/<pid>/root
	echo "This test only runs only Linux."
	exit 77
fi

if [ -z "$(type -P df)" ]; then
	echo "This test requires the 'df' tool."
	exit 77
fi

ROOT=${abs_top_builddir:-$(dirname "$0")/..}
TESTDIR=${abs_top_testdir:-$(dirname "$0")}

PID_FILE=/swtpm.pid
VTPM_NAME="vtpm-test-chroot"
SWTPM_DEV_NAME="/dev/${VTPM_NAME}"

source "${TESTDIR}/common"
source "${TESTDIR}/test_common"
source "${TESTDIR}/test_cuse"

skip_test_no_tpm20 "${SWTPM_EXE}"

trap "cleanup" SIGTERM EXIT

function cleanup()
{
	rm -rf "$TPMDIR"
	if [ -n "$PID" ]; then
		kill_quiet -SIGTERM "$PID" 2>/dev/null
	fi
}

for OPTION in --chroot -R; do
	TPMDIR="$(mktemp -d)" || exit 1

	# CUSE TPM will only work if the filesystem does not have 'nodev' option
	mnt=$(df "$TPMDIR" | tail -n 1 | gawk '{print $1" "$6}')
	if [ -z "${mnt}" ]; then
		echo " Error: Could not determine filesystem and mount point of $TPMDIR"
		exit 1
	fi
	nodev="$(grep -E "^${mnt} " /proc/mounts |
		 gawk '{print ","$4","}' |
		 grep ",nodev,")"
	if [ -n "${nodev}" ]; then
		echo " Error: '${mnt}' is mounted with nodev option. Skipping test."
		exit 77
	fi

	mkdir "$TPMDIR/dev"
	mknod -m 0666 "$TPMDIR/dev/null" c 1 3     #  due to daemonize_prep()
	mknod -m 0666 "$TPMDIR/dev/urandom" c 1 9
	mknod -m 0666 "$TPMDIR/dev/cuse" c 10 203

	$SWTPM_EXE cuse \
		-n "$SWTPM_DEV_NAME" \
		"$OPTION" "$TPMDIR" \
		--tpmstate dir=/ \
		--pid "file=$PID_FILE" \
		--tpm2 \
		--flags not-need-init \
		${SWTPM_TEST_SECCOMP_OPT:+${SWTPM_TEST_SECCOMP_OPT}} &>/dev/null &

	if wait_for_file "$TPMDIR/$PID_FILE" 3; then
		echo "Error: CUSE TPM did not write pidfile."
		exit 1
	fi

	PID=$(ps aux |
		grep "cuse" |
		grep " ${SWTPM_DEV_NAME}" |
		grep -v grep |
		gawk '{print $2}')

	validate_pidfile "$PID" "$TPMDIR/$PID_FILE"

	if [ "$(readlink "/proc/$PID/root")" != "$TPMDIR" ]; then
		echo "Test 1 failed: Unexpected chroot dir"
		exit 1
	fi

	if [ ! -f "${TPMDIR}/tpm2-00.permall" ]; then
		echo "Missing state file"
		exit 1
	fi

	echo "Test $OPTION passed"
	cleanup
done
